import Vue from 'vue'
import { loadScriptQueue } from '@/utils/loadScript'
import axios from 'axios'
import Tinymce from '@/components/tinymce/index.vue'
import {
  makeUpHtml, vueTemplate, vueScript, cssStyle
} from '@/components/generator/html'
import { makeUpJs } from '@/components/generator/js'
import { makeUpCss } from '@/components/generator/css'
import { exportDefault, beautifierConf, titleCase } from '@/utils/index'
import loadBeautifier from '@/utils/loadBeautifier'

Vue.component('tinymce', Tinymce)
Vue.prototype.$axios = axios

const $previewApp = document.getElementById('showviewApp')
const childAttrs = {
  file: '',
  dialog: ' width="600px" class="dialog-width" v-if="visible" :visible.sync="visible" :modal-append-to-body="false" '
}

window.addEventListener('message', init, false)

function buildLinks(links) {
  let strs = ''
  links.forEach(url => {
    strs += `<link href="${url}" rel="stylesheet">`
  })
  return strs
}

const editorObj = {
  html: null,
  js: null,
  css: null
}

const mode = {
  html: 'html',
  js: 'javascript',
  css: 'css'
}
let beautifier

function init(event) {
  if (event.data.type === 'refresh') {
    const { fields, formConf } = event.data
    const formData = {
      fields,
      ...formConf
    }
    console.log('++++++', formData)
    const type = 'file'
    let htmlCode = makeUpHtml(formData, type)
    let jsCode = makeUpJs(formData, type)
    let cssCode = makeUpCss(formData)

    loadBeautifier(btf => {
      beautifier = btf
      htmlCode = beautifier.html(htmlCode, beautifierConf.html)
      jsCode = beautifier.js(jsCode, beautifierConf.js)
      cssCode = beautifier.css(cssCode, beautifierConf.html)
    })

    const postData = {
      type: 'refreshFrame',
      data: {
        generateConf: this.generateConf,
        html: htmlCode,
        js: jsCode.replace(exportDefault, ''),
        css: cssCode,
        scripts: [],
        links: []
      }
    }

    if (postData.type === 'refreshFrame') {
      const code = postData.data
      const attrs = childAttrs.file
      let links = ''

      if (Array.isArray(code.links) && code.links.length > 0) {
        links = buildLinks(code.links)
      }

      $previewApp.innerHTML = `${links}<style>${code.css}</style><div id="app"></div>`

      if (Array.isArray(code.scripts) && code.scripts.length > 0) {
        loadScriptQueue(code.scripts, () => {
          newVue(attrs, code.js, code.html)
        })
      } else {
        newVue(attrs, code.js, code.html)
      }
    }
  }
}

function newVue(attrs, main, html) {
  main = eval(`(${main})`)
  main.template = `<div>${html}</div>`
  new Vue({
    components: {
      child: main
    },
    data() {
      return {
        visible: true
      }
    },
    template: `<div><child ${attrs}/></div>`
  }).$mount('#app')
}
